
import axios from 'axios';

import { ElNotification } from 'element-plus'
import "element-plus/es/components/notification/style/css"

import { useRouter } from 'vue-router'

// var $router = useRouter()

import $router from '../router/index'

//实例化axios
var service = axios.create({
    timeout: 10 * 1000, //超时时间
    baseURL: '', //基准路径
})

//设置拦截器
service.interceptors.request.use(
    (config)=>{
        //设置请求头参数
        config.headers['Authorization'] = 'Bearer' + ' ' + localStorage.getItem('token');

        return config;
    },
    (error)=>{
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    (res)=>{
        return res;
    },
    (error)=>{
        if( error.response.status == 401 ){
            //弹框
            ElNotification({
                title: '提示',
                message: '登陆过期,请重新登录!',
                type: 'warning',
            })
            //删除token
            localStorage.removeItem('token');
            //重定向到登录页
            $router.push('/login');

        }else if(  error.response.status == 404 ){
            
            ElNotification({
                title: '提示',
                message: '访问路径有误!',
                type: 'warning',
            })
        }else if(  error.response.status == 500 ){
            
            ElNotification({
                title: '提示',
                message: '服务器内部错误!',
                type: 'warning',
            })
        }
        return Promise.reject(error)
    }
)

export default service;